
var DEFAULT_SETTING = {
  "hypertopic" :
  {
    "url" : "http://argos.test.hypertopic.org/",
    "username" : "argos",
    "password" : "argos"
  },

  "webdav" :
  {
    "url" : "http://webdav.example.com/",
    "username" : "webdav",
    "password" : "webdav"
  }
}

const EXT_NAME = "LASULI";
const DEBUG = "console"; //logger, console or dump or ""
const PREF_PREFIX = "extensions.lasuli.";
const PREF_TEMPLATE_PREFIX = "extensions.lasuli.template.";
const PORPHYRY_PREFIX = "http://porphyry.sf.net/start.php?service=";
//const COLORS = new Array("hsl(220,62%,74%)", "hsl(44,100%,73%)", "hsl(81,32%,71%)", "hsl(359,73%,78%)", "hsl(260,50%,77%)");
const COLORS = new Array("#486FBD", "#BA8900", "#A1B57B", "#C73638", "#8362C4");
const HTMLNS = "http://www.w3.org/1999/xhtml";
const HIGHLIGHT_PHPSCRIPT = "http://www.smess.egss.ulg.ac.be/sandbox/highlight.php?";
const FRAGMENT_PHPSCRIPT = "http://www.smess.egss.ulg.ac.be/sandbox/fragment.php?";

const MARK_SELECTION_START = '[[[\u200B\u200B\u200B\u200B\u200B';
const MARK_SELECTION_END = '\u200B\u200B\u200B\u200B\u200B\u200B\u200B]]]';
const HIGHLIGHT_TAG = "<!-- highlighted_by_lasuli_sidebar //-->";
const COLORENTITY_PREFIX = "entity/colorIndex/";

var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                   .getInterface(Components.interfaces.nsIWebNavigation)
                   .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
                   .rootTreeItem
                   .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                   .getInterface(Components.interfaces.nsIDOMWindow);
var windowMediator = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                     .getService(Components.interfaces.nsIWindowMediator);

function getRecentWindow() {
  return windowMediator.getMostRecentWindow("navigator:browser");
}

function getCurrentUri(){
  var currentUri = (typeof(locationBarListener) != "undefined" && locationBarListener.uri != null) ? locationBarListener.uri :
                              mainWindow.content.location.href;
  if(currentUri.indexOf("#") > 0)
    currentUri = currentUri.substring(0,currentUri.indexOf("#"));
  return currentUri;
}
function getRecentUri() {
  var recentWindow = getRecentWindow();
  return recentWindow ? recentWindow.content.document.location : null;
}
function getRecentContent(){
  var recentWindow = getRecentWindow();
  return recentWindow ? recentWindow.content.document.documentElement.textContent : null;
}
function oc(a)
{
  var o = {};
  for(var i=0;i<a.length;i++)
  {
    o[a[i]]='';
  }
  return o;
}

function colorCalc(a,b){
  var R1,R2,G1,G2,B1,B2,R,G,B;
  try{
    R1 = parseInt(a.substring(1,3),16);
    G1 = parseInt(a.substring(3,5),16);
    B1 = parseInt(a.substring(5,7),16);
    R2 = parseInt(a.substring(1,3),16);
    G2 = parseInt(a.substring(3,5),16);
    B2 = parseInt(a.substring(5,7),16);
    R=R1+R2-255;
    G=G1+G2-255;
    B=B1+B2-255;
    R = (R>0)?R.toString(16):"00";
    G = (G>0)?G.toString(16):"00";
    B = (B>0)?B.toString(16):"00";
    R = R.length < 2? "0" + R: R;
    G = G.length < 2? "0" + G: G;
    B = B.length < 2? "0" + B: B;
  }catch(e){}
  return "#" + R + G + B;
}

function getContents(aURL){
  /*var ioService=Components.classes["@mozilla.org/network/io-service;1"]
    .getService(Components.interfaces.nsIIOService);
  var scriptableStream=Components
    .classes["@mozilla.org/scriptableinputstream;1"]
    .getService(Components.interfaces.nsIScriptableInputStream);

  var channel=ioService.newChannel(aURL,null,null);
  var input=channel.open();
  scriptableStream.init(input);
  var str=scriptableStream.read(input.available());
  scriptableStream.close();
  input.close();
  return str;*/
  var ioserv = Components.classes["@mozilla.org/network/io-service;1"]
    .getService(Components.interfaces.nsIIOService);
  var channel = ioserv.newChannel(aURL, 0, null);
  var stream = channel.open();

  if (channel instanceof Components.interfaces.nsIHttpChannel && channel.responseStatus != 200) {
    return "";
  }

  var bstream = Components.classes["@mozilla.org/binaryinputstream;1"]
    .createInstance(Components.interfaces.nsIBinaryInputStream);
  bstream.setInputStream(stream);

  var size = 0;
  var file_data = "";
  while(size = bstream.available()) {
    file_data += bstream.readBytes(size);
  }

  return file_data;
}

function saveToLocal(uri){
  //var file = Components.classes["@mozilla.org/file/local;1"]
  //            .createInstance(Components.interfaces.nsILocalFile);
  //file.initWithPath("C:\\download.tmp");
  var file = Components.classes["@mozilla.org/file/directory_service;1"].
                     getService(Components.interfaces.nsIProperties).
                     get("TmpD", Components.interfaces.nsIFile);
  file.append("webdav.tmp");
  //file.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0666);

  var wbp = Components.classes['@mozilla.org/embedding/browser/nsWebBrowserPersist;1']
            .createInstance(Components.interfaces.nsIWebBrowserPersist);
  var ios = Components.classes['@mozilla.org/network/io-service;1']
            .getService(Components.interfaces.nsIIOService);
  var uri = ios.newURI(uri, null, null);
  wbp.persistFlags &= ~Components.interfaces.nsIWebBrowserPersist.PERSIST_FLAGS_NO_CONVERSION; // don't save gzipped
  wbp.saveURI(uri, null, null, null, null, file);
  return file.path;
}

function putToRemote(tmpfile, uri){
  var file = Components.classes["@mozilla.org/file/local;1"]
              .createInstance(Components.interfaces.nsILocalFile);
  file.initWithPath(tmpfile);

  debug("[global.js::putToRemote] file" + file.path, 4);
  // Make a stream from a file.
  var stream = Components.classes["@mozilla.org/network/file-input-stream;1"]
                         .createInstance(Components.interfaces.nsIFileInputStream);
  stream.init(file, 0x04 | 0x08, 0644, 0x04); // file is an nsIFile instance

  // Try to determine the MIME type of the file
  var mimeType = "text/plain";
  try {
    var mimeService = Components.classes["@mozilla.org/mime;1"]
            .createInstance(Components.interfaces.nsIMIMEService);
    mimeType = mimeService.getTypeFromFile(file); // file is an nsIFile instance
  }
  catch(e) { debug("[global.js::putToRemote] e: " + e, 4); }

  debug("[global.js::putToRemote] mimeType" + mimeType, 4);

  // Send
  var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
                      .createInstance(Components.interfaces.nsIXMLHttpRequest);
  req.open('PUT', uri, false); /* synchronous! */
  req.setRequestHeader('Content-Type', mimeType);
  req.send(stream);
  var statusCode = req.status + "";
  if ( statusCode.substr(0,1) != "2" )
      return false;
  else
      return true;
}

String.prototype.isUrl = function() {
  var regexp = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
  return regexp.test(this);
};
String.prototype.trim = function () {
  var str = this.replace(/^\s+/, '');
	for (var i = str.length - 1; i >= 0; i--) {
		if (/\S/.test(str.charAt(i))) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return str;
};

String.prototype.trimNewLine = function () {
  return this.replace(/^\n/, '').replace(/\n$/, '');
}
String.prototype.toXml = function(){
    return this.replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;");
};

String.prototype.startsWith = function(prefix) {
  if (this) return( (this.substring(0, prefix.length) == prefix) ); else return false;
};
String.prototype.endsWith = function(str) {
    return (this.length-str.length)==this.lastIndexOf(str);
};
Array.prototype.sortNum = function() {
   return this.sort( function (a,b) { return a.startPos-b.startPos; } );
}
Array.prototype.lastIndexOf = function( v, b, s ) {
 b = +b || 0;
 var i = this.length; while(i-->b) {
  if( this[i]===v || s && this[i]==v ) { return i; }
 }
 return -1;
};
Array.prototype.unique = function( b ) {
 var a = [], i, l = this.length;
 for( i=0; i<l; i++ ) {
  if( a.indexOf( this[i], 0, b ) < 0 ) { a.push( this[i] ); }
 }
 return a;
};
